<template>
  <div>
    <MainBox>
      <template #headerForm>
        <el-form :inline="true" :model="params" class="demo-form-inline">
          <el-form-item label="点位搜索">
            <el-input v-model="params.name" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="区域搜索">
            <el-select v-model="params.regionId" clearable placeholder="请选择">
              <el-option v-for="item in pointList" :key="item.id" :label="item.region.name" :value="item.regionId" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="onSubmit">查询</el-button>
          </el-form-item>
        </el-form>
      </template>
      <template #table>
        <el-button
          type="danger"
          icon="iconfont icon-zengjiatianjiajiahao"
          @click="showDialog"
        >新建</el-button>
        <el-table :data="list" style="width: 100% ">
          <el-table-column type="index" label="序号" width="80" />
          <el-table-column prop="name" label="点位名称" />
          <el-table-column prop="region.name" label="所在区域" />
          <el-table-column prop="businessType.name" label="商圈类型" />
          <el-table-column prop="ownerName" label="合作商" />
          <el-table-column prop="addr" label="详细地址" />
          <el-table-column label="操作">
            <template #default="scope">
              <el-button type="text" @click="areaInfo(scope.row)">查看详情</el-button>
              <el-button type="text" @click="modifyFn(scope.row)">修改</el-button>
              <el-button type="text" class="del" @click="delFn(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="fotter">
          <div class="left">
            {{ totalNum }}
          </div>
          <div class="right">
            <el-button-group>
              <el-button :disabled="params.pageIndex === 1" type="primary" icon="el-icon-arrow-left" @click="prevFn">上一页</el-button>
              <el-button :disabled="params.pageIndex >= totalPage" type="primary" @click="nextFn">下一页<i class="el-icon-arrow-right el-icon--right" /></el-button>
            </el-button-group>
          </div>
        </div>
      </template>
    </MainBox>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="30%"
      @close="handleClose"
      @open="handleOpen"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" class="demo-ruleForm">
        <el-form-item label="点位名称" prop="name">
          <el-input v-model="formData.name" show-word-limit maxlength="15" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="所在区域" prop="regionId">
          <el-select v-model="formData.regionId" placeholder="请选择">
            <el-option v-for="item in pointList" :key="item.id" :label="item.region.name" :value="item.regionId" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属商圈" prop="businessId">
          <el-select v-model="formData.businessId" placeholder="请选择">
            <el-option v-for="item in businessType" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="归属合作商" prop="ownerId">
          <el-select v-model="formData.ownerId" placeholder="请选择">
            <el-option v-for="item in partherList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="详细地址" prop="areaCode">
          <el-cascader
            v-model="formData.areaCode"
            placeholder="请选择"
            :options="cityList"
            :props="{ checkStrictly: true }"
            @change="change"
          />
        </el-form-item>
        <el-form-item prop="addr">
          <el-input v-model="formData.addr" show-word-limit maxlength="60" type="textarea" placeholder="请输入详细地址" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="addFn">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="点位详情"
      :visible.sync="isShowDialog"
      width="30%"
      @close="close"
    >
      <el-table :data="infoList" style="width: 100%" height="500px">
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="innerCode" label="机器编号" width="100" />
        <el-table-column prop="vmStatus" label="设备状态" width="100" />
        <el-table-column prop="lastSupplyTime" label="最后一次供货时间" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { regionData, CodeToText } from 'element-china-area-data'
import { searchParther, businessType, daddPoint, delPoint, pointInfo, pointSearch, montifyPoint } from '@/api'
export default {
  data() {
    return {
      isShowDialog: false,
      formData: {
        name: '',
        addr: '',
        areaCode: '',
        createUserId: this.$store.getters.id,
        regionId: '',
        businessId: '',
        ownerId: '',
        ownerName: ''
      },
      formRules: {
        name: [{ required: true, message: '此项为必填项', tigger: 'blur' }],
        addr: [{ required: true, message: '此项为必填项', tigger: 'blur' }],
        areaCode: [{ required: true, message: '此项为必填项', tigger: 'blur' }],
        regionId: [{ required: true, message: '此项为必填项', tigger: 'blur' }],
        businessId: [{ type: 'number', required: true, message: '此项为必填项', tigger: 'blur' }],
        ownerId: [{ type: 'number', required: true, message: '此项为必填项', tigger: 'blur' }]
      },
      // 新建  修改 对话框
      dialogVisible: false,
      // 接口数据
      params: {
        pageIndex: 1,
        pageSize: 10,
        name: '',
        regionId: ''
      },
      // 表格底部显示数据
      totalNum: 0,
      // 数据总数
      totalCount: 0,
      // 数据页数
      totalPage: 0,
      // 列表数据
      list: [],
      tableData: [],
      pointList: [],
      infoList: [],
      // 商圈类型
      businessType: [],
      // 合作商列表
      partherList: [],
      cityList: [],
      arr: []
    }
  },
  computed: {
    title() {
      return this.formData.id ? '修改区域' : '新增区域'
    }
  },
  async created() {
    this.cityList = regionData
    const { data } = await pointSearch(this.params)
    // console.log(res)
    this.pointList = data.currentPageRecords
    this.fetchAreaList()
  },
  methods: {
    change(val) {
      this.arr = val.map(item => CodeToText[item])
      // console.log(val)
      this.formData.areaCode = val.at(-1)
    },
    async handleOpen() {
      console.log(regionData)
      console.log(CodeToText)
      // 获取商圈类型
      const { data } = await businessType()
      // console.log(res)
      this.businessType = data
      const res = await searchParther({
        pageIndex: 1, pageSize: 10, name: ''
      })
      // console.log(res)
      this.partherList = res.data.currentPageRecords
    },
    close() {
      this.isShowDialog = false
    },
    async areaInfo(val) {
      this.isShowDialog = true
      const { data } = await pointInfo(val.id)
      console.log(data)
      this.infoList = data.map(item => {
        switch (+item.vmStatus) {
          case 0:
            item.vmStatus = '未投放'
            break
          case 1:
            item.vmStatus = '运营'
            break
          case 2:
            item.vmStatus = '撤机'
            break
          default:
            break
        }
        item.lastSupplyTime = item.lastSupplyTime.replace('T', ' ')
        return item
      })
    },
    // 删除区域
    delFn(val) {
      this.$confirm('确定要删除吗？', '提示', {
        confirmButtonText: '狠心删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          await delPoint(val.id)
          if (this.params.pageIndex > 1 && this.list.length === 1) this.params.pageIndex--
          this.fetchAreaList()
          this.$message.success('删除成功')
        } catch (error) {
          this.$message.error(error.response.data)
        }
      })
    },
    // modifyFn修改区域
    modifyFn(val) {
      this.dialogVisible = true
      this.formData = {
        ...val,
        regionName: val.name
      }
    },
    async addFn() {
      console.log(this.formData.id)
      this.$refs.formRef.validate(async volid => {
        try {
          if (!volid) return
          if (!this.formData.id) {
            this.formData.addr = this.arr.length !== 0 ? this.arr.join('-') + '-' + this.formData.addr : this.formData.addr
            const parther = this.partherList.find(item => item.id === this.formData.ownerId)
            await daddPoint({
              ...this.formData,
              ownerName: parther.name
            })
          } else {
            await montifyPoint(this.formData)
          }
          this.$message.success(this.title + '成功')
          this.handleClose()
          this.fetchAreaList()
        } catch (error) {
          console.dir(error)
          this.$message.error(error.response.data)
        }
      })
    },
    // 新建函数
    showDialog() {
      this.dialogVisible = true
    },
    // 弹窗关闭
    handleClose() {
      this.dialogVisible = false
      this.$refs.formRef.resetFields()
      this.formData = {
        name: '',
        addr: '',
        areaCode: '',
        createUserId: this.$store.getters.id,
        regionId: '',
        businessId: '',
        ownerId: '',
        ownerName: ''
      }
      this.arr = []
    },
    // 翻页函数
    prevFn() {
      this.params.pageIndex > 1 ? this.params.pageIndex-- : ''
      this.fetchAreaList()
    },
    nextFn() {
      this.params.pageIndex < this.totalPage ? this.params.pageIndex++ : ''
      this.fetchAreaList()
    },
    onSubmit() {
      this.fetchAreaList()
    },
    // 获取列表
    async fetchAreaList() {
      const { data } = await pointSearch(this.params)
      // console.log('', data)
      this.totalPage = data.totalPage
      this.totalNum = `共${data.totalCount}条记录  第${data.pageIndex}/${data.totalPage}页`
      this.list = data.currentPageRecords
    }
  }
}

</script>

<style lang="scss" scoped>
.el-button.del {
  color: red;
}
.el-descriptions-item__container{
.labelClassName {
  flex: 1;
  color: #909;
  background-color: #303;
}
}
.el-select,.el-cascader {
  width: 100%;
}

</style>
